package com.lqk.demo.pessimisticlock.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lqk
 * @date 2021/12/23 9:52
 */
@Slf4j
public class ReentrantLock3 {
    /**
     * 锁超时
     */
    private static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            log.debug("尝试获得锁");
            try {
                if (!lock.tryLock(2, TimeUnit.SECONDS)){
                    log.debug("获取不到锁");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("获取不到锁2");
                return;
            }
            try{
                log.debug("获取到锁");
            }finally {
                lock.unlock();
            }

        }, "t1");

        lock.lock();
        log.debug("主线程获得到锁");
        TimeUnit.SECONDS.sleep(1);
        lock.unlock();
        t1.start();
    }
}
